import json
import random
import time
import redis
import requests
from flask import Blueprint, send_file, make_response, redirect
from flask_restful import Resource,Api
from ronglian_sms_sdk import SmsSDK
from tools.my_jwt import jj
from app import db
from tools.captcha.captcha import captcha
from tools.comm import send_message , get_ali_object
from tools.myredis import r
from application.models.users.user import SfLogin
from application.models.users.user import *
from flask_restful import reqparse
from flask import Blueprint,request,jsonify
user_blue = Blueprint("userblue",__name__)
api = Api(user_blue)
from captcha.image import ImageCaptcha
# @user_blue.route('/text')
# def get():
#     return jsonify({'code':200,'msg':'mes'})

@user_blue.route('/getcode')
def get_img():
    name,text,img=captcha.generate_captcha()
    uuid=request.args.get('uuid')
    r.str_add(uuid,text)
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>",cls.get(uuid))
    res=make_response(img)
    res.headers['Content-Type']="image/jpg"
    return res

@user_blue.route("/sendSmsCode",methods=["POST"])
def sendSmsCode():
    data = request.data
    # 获取3个参数
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        print(piccode,'>>>>>>>>>>>>>>>>')
        mobile = data['mobile']
        value = r.str_get(uuid)
        value1 = value.decode()
        print(value1)
        if value:
            if piccode.lower()==value1.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
                scode = random.randint(10000,99999)
                flag = send_message(mobile,scode)
                if flag:
                    r.str_setex(mobile,scode,60)
                    r.del_key(uuid)
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code':10013,'msg':'发送验证码错误'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})
        else:
            return jsonify({'code':10010,'msg':'图片验证码不存在'})

import time
# 发送短信接口
@user_blue.route("/login",methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        mcode = data["code"]
        mobile = data["mobile"]
        code = r.str_get(mobile)
        if code:
            if int(code)==int(mcode):
                user = User.query.filter(User.mobile==mobile).first()
                if user:
                    r.del_key(mobile)
                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile==mobile).first()
                token = str(random.randint(100,1000))
                return jsonify({"code":200,"msg":"发送成功","token":token,"userid":user.id})
        else:
            return jsonify({"code":10021,"mes":"验证码不存在"})
    else:
        return jsonify({"code":10020,"mes":"数据不完整"})

# 获取weibo地址
@user_blue.route('/sf_login')
def getwburl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code":200,"url":url})

# weibo回调接口
@user_blue.route('/user/weiboCallback/')
def weiboCallback():
    # 获取code
    code = request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    # 查询数据库中是否存在，如果存在用户信息生成jwt token 返回
    sql = 'select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid=%s'%(uid)
    user = db.session.execute(sql)
    if user:
        for i in user:
            data = {'data':{'userid':i[0],'exp':int(time.time())}}
            token = jj.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?userid=" + str(i[0]) + "&token=" + token)
    # 不存在跳转到vue绑定页面，token uid 传递过去
    return redirect("http://localhost:8080/#/binMobile?uid="+uid+"&token="+token)

# 绑定手机号
@user_blue.route('/binMobile',methods=['POST'])
def binMobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    uid = data['uid']
    token = data['token']
    print(mobile,'>>>>>>>>>>>>>>>>>>>>>>>>>..')
    # 先查询用户表，如果手机号存在，获取userid,写入三方登录表，生成token返回
    user = User.query.filter(User.mobile==mobile).first()
    print(user)
    if not user:
        # 添加用户
        u = User(mobile=mobile,nikename=mobile)
        print(u)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile==mobile).first()
    sfuser = SfLogin(userid=user.id, webfrom='wb', uid=uid, token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 如果不存在，写入user表
    # 获取userid,写入三方登录表，生成token返回
    data = {'data':user.id,'exp':int(time.time())}
    token = jj.jwt_encode(data)
    return jsonify({'userid':str(user.id),'token':token})


# 测试
@user_blue.route("/test")
def test():
    orderon = 12345566
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='test' + "充值服务",  # 商品简单描述
        out_trade_no=orderon,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })



from application.models.users.user import VipRecord
# 购买vip生成订单
@user_blue.route('/buy',methods=['POST'])
def buy():
    # 获取参数
    data = json.loads(request.data)
    userid = data['userid']
    year = data['year']
    money = 200
    # 生成订单
    tmoney = money * int(year)
    order_no = str(int(time.time()))+str(userid)+str(random.randint(100,999))
    Viprecord = VipRecord(order_no=order_no,userid=userid,year=year,money=tmoney,active_money=tmoney,status=1)
    db.session.add(Viprecord)
    db.session.commit()
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='test',  # "充值服务",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })


from application.models.users.user import Vip
@user_blue.route('/callback')
def callback():
    # 接收参数
    data = request.args
    datames = {k:v for k,v in data.items()}
    # 删除字段中的key为sign的记录
    sign = datames.pop('sign')
    # 鉴权 订单号 流水号
    pay = get_ali_object()
    flag = pay.verify(datames,sign)

    if flag==True:
        # 支付宝流水号
        transaction_no = datames['trade_no']
        # 订单号
        order_no = datames['out_trade_no']
        # 事务处理
        try:
            # 订单号更新订单表
            record = VipRecord.query.filter(VipRecord.order_no==order_no).first()
            record.status=2
            record.transaction_no = transaction_no
            db.session.add(record)
            # 更新用户表
            User.query.filter(User.id==record.userid).update({'level':2})
            # 更新vip表
            vip = Vip.query.filter(Vip.userid==record.userid,Vip.status==1).first()
            if vip is not None:
                # 结束时间+购买时间
                etime = vip.e_time.split("-")
                tyear = int(etime[0])+int(record.year)
                yearstr = "-"
                etime[0] = str(tyear)
                retime = yearstr.join(etime)
                vip.e_time = retime
                db.session.add(vip)
            else:
                nowyear = datetime.date.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%m:%s")
                etime = nowyear.split("-")
                tyear = int(etime[0])+int(record.year)
                etime[0] = str(tyear)
                yearstr = "-"
                retime = yearstr.join(etime)
                vip = Vip(userid = record.userid.userid,s_time=datetime.datetime.now(),e_time=retime)
                db.session.add(vip)
            db.session.commit()
        except:
            db.rollback()
    else:
        print('鉴权失败')
    return redirect('http://localhost:8080/#/vip')


@user_blue.route('/getTags')
def getTags():
    tags = Tags.query.all()
    tagslist = [{'id':i.id,'name':i.name}for i in tags]
    ctype = Ctype.query.all()
    ctypelist = [{'id':i.id,'name':i.name}for i in ctype]
    course = CourseType.query.all()
    courselist = [{'id':i.id,'name':i.name}for i in course]
    return jsonify({'code':200,'tags':tagslist,'ctype':ctypelist,'course':courselist})

from db import db
@user_blue.route('/getid')
# def getRoleResoure():
#     id = request.args.get("id")
#     print("id", id)
#     if not id:
#         return jsonify({"code":400,"msg":"数据不存在"})
#     sql = "select * from tags where id=%d" % int(str(id))
#     res = db.findAll(sql)
#     # list = [i['resourceid'] for i in res]
#     # 重组数据返回
#     print(res)
#     return jsonify({"code": 200, 'data': res})
def getRoleResoure():
    id = request.args.get("id")
    print("id", id)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course as c inner join course_tag as ct on ct.courseid=c.id where ct.tagid=" + id
    res = db.findAll(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})

import math
@user_blue.route('/getvip')
def get():
    id = request.args.get("id")
    print(id)
    if not id:
        return jsonify({'code': 400, 'msg': '数据不存在'})
    # 免费
    if int(id) == 2:
        sql = "select * from course where is_vip=0"
        res = db.findAll(sql)
        return jsonify({'code': 200, 'getvip': res})
    # 会员
    if int(id) == 3:
        tsql = "select * from course where is_vip=1"
        tres = db.findAll(tsql)
        return jsonify({'code': 200, 'getvip': tres})
    # 全部
    else:
        qsql = "select * from course"
        qres = db.findAll(qsql)
        return jsonify({'code': 200, 'getvip': qres})

@user_blue.route('/getpub')
def GetIs_publish():
    id = request.args.get("id")
    print("id", id)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course where is_publish=%d"%int(id)
    res = db.findAll(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})


@user_blue.route('/hew_hot')
def Get_hew_hot():
    type = request.args.get("type")
    print("id", id)
    if not type:
        return jsonify({'code':400,'msg':'数据不存在'})
    if type == 'hew':
        sql = "select * from course order by create_time desc"
        res = db.findAll(sql)
        print(res)
        return jsonify({"code": 200, 'data': res})
    else:
        sql1 = 'select * from course order by views desc'
        ress = db.findAll(sql1)
        print(ress)
        return jsonify({"code": 200, 'data': ress})
# # 七牛获取token
# from qiniu import Auth
# #需要填写你的 Access Key 和 Secret Key
# @user_blue.route("/get_qntoken")
# def get_qntoken():
#     access_key = 'b4N2i0GoS4dGm6yqrAT7co0xhvKYLNPITckKkk_L'
#     secret_key = 'KrTWEQLlmo5DbO1DeA2-gbwLER48A9x2NydgDkqv'
#     #构建鉴权对象
#     q = Auth(access_key, secret_key)
#     #要上传的空间
#     bucket_name = '2203a'
#     #生成上传 Token，可以指定过期时间等
#     token = q.upload_token(bucket_name)
#     return jsonify({"code": 200, "msg":"获取成功","token":token})

# @user_blue.route("/getCourse")
# def getCourse():
#     #获取参数page
#     page = int(request.args.get("page"))
#     #获取上线，即将上线条件
#     online = int(request.args.get("is_publish"))
#     #查询总条数
#     total = Course.query.count()
#     #定义每页显示多少条
#     page_size=2
#     #查询当前页面记录
#     start = math.ceil((page-1)*page_size)
#     #select * from course limit start,page_size
#     #获取排序字段
#     orderpara = request.args.get("orderpara")
#     if orderpara == 'new':
#         course = Course.query.order_by(Course.create_time).filter(Course.is_publish==online).offset(start).limit(page_size).all()
#     list = [{"id":i.id,"name":i.name,"url":i.url,"views":i.views} for i in course]
    # 返回结果
    # return jsonify({"code":200,"clist":list,"total":total,"page_size":page_size})

# 获取章节
@user_blue.route('/getjie')
def Get_Jie():
    id = request.args.get("id")
    print(id,11111111111111111111111111111111)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from jie where jie.courseid=%d"%int(id)
    res = db.findAll(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})

# 获取课程所有数据
@user_blue.route('/get_course')
def Get_course():
    id = request.args.get("id")
    print(id,11111111111111111111111111111111)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course where id=%d"%int(id)
    res = db.findAll(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})
# #获取最近浏览
# @user_blue.route("/getViews")
# def getViews():
#     #获取id
#     userid = request.args.get("userid")
#     findkey = "collection"+str(userid)+"*"
#     gidlist = r.getvalues(findkey)
#     reslist = []
#     for i in gidlist:
#         goods = r.gettall_hash(i)
#         dict={}
#         for k,v in goods.items():
#             kk = k.decode()
#             vv = v.decode()
#             dict[kk] = vv
#         reslist.append(dict)
#     return jsonify({"code":200,"list":reslist})

# 获取训练营里面得所有数据

@user_blue.route('/getxly')
def getxly():
    sql = 'select * from tcourse'
    res = db.findAll(sql)
    return jsonify({'code':200,'msg':'ok','data':res})

# 加入购物车
@user_blue.route('/addgood',methods=["POST"])
def addshop():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()
    print(args['userid'])
    print(args['id'])

    if not all({args['userid'],args['id']}):
        return jsonify({'code':400,'msg':'数据不存在'})

    cart = Cart.query.filter(Cart.cid == args['id']).first()
    print(cart)
    if cart:
        sql = "update cart set count=count+1 where cart.cid=%d"%int(args['id'])
        db.add(sql)
        db.commit()
        return jsonify({'code':200,'msg':'ok'})
    else:
        count = 1
        sql = "insert into cart(userid,cid,count) values('%d','%d','%d')"%(int(args['userid']),int(args['id']),int(count))
        db.add(sql)
        db.commit()
        return jsonify({'code':200,'msg':'加入购物车成功'})

# 展示购物车数据
@user_blue.route('/getcourse')
def gettcourse():
    uid = request.args.get('userid')
    list = []
    sql = "select * from cart where cart.userid=%d"% int(uid)
    res = db.findAll(sql)
    for i in res:
        sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
        res1 = db.findAll(sql1)
        for j in res1:
            list.append({
                'id':j['id'],
                'title':j['title'],
                'price':j['price'],
                'count':i['count'],
                'url':j['url'],
                'amount':(j['price'] * i['count'])
            })
    return jsonify({'code':200,'msg':'ok','res':list})

# 购物车数量加
@user_blue.route('/addcount',methods=["POST"])
def Add_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()
    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})
    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.findAll(sql)
    for i in res:
        sql1 = "update cart set count=count+1 where cart.userid=%d and cart.cid=%d" % (
        int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code':200,'msg':'ok'})


# 购物车数量减
@user_blue.route('/mincount',methods=["POST"])
def Min_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()
    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})
    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.findAll(sql)
    for i in res:
        sql1 = "update Cart set count=count-1 where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code':200,'msg':'ok'})

# 删除购物车数据
@user_blue.route('/delcount',methods=["POST"])
def Del_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()
    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})
    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.findAll(sql)
    for i in res:
        sql1 = "delete from cart where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code':200,'msg':'ok'})

# 提交订单
# from tools.comm import get_ali_object
# @user_blue.route("/settlement",methods=["POST"])
# # def settlement():
# #     data=json.loads(request.data)
# #     userid=int(data["userid"])
# #     tmoney=int(data["tmoney"])
# #     cid=int(data["cid"])
# #     #幂等性token
# #     key = "mdtoken" + str(userid)
# #     sum=0
# #     sql = "select * from cart where userid=%d" % userid
# #     res=db.session.execute(sql)
# #     if not res:
# #         return jsonify({"code":500,"msg":"没有该商品"})
# #     sum+=float(tmoney)
# #     print(sum)
# #     # 订单号
# #     number = int(str(userid) + str(random.randint(1000, 9999)))
# #     create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
# #     update_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
# #     status = 2
# #     try:
# #         usql = vipuser_course(courseid=cid,userid=userid)
# #         db.session.add(usql)
# #         isql = Orders(create_time=create_time,update_time=update_time,userid=userid,courseid=cid,number=number,tmoney=sum,status=status,price=sum)
# #         db.session.add(isql)
# #         sqlcart = Cart.query.filter(Cart.userid==userid).first()
# #         db.session.delete(sqlcart)
# #         print(">><<")
# #         db.session.commit()
# #     except:
# #         db.session.rollback()
# #     #删除幂等性token
# #     r.del_key(key)
# #     # 支付
# #     oreder_no = str(number) + "," + str(2)
# #     alipay = get_ali_object()
# #     query_params = alipay.direct_pay(
# #         subject=str(userid) + "购买课程",  # 商品简单描述
# #         out_trade_no=oreder_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
# #         total_amount=sum,  # 交易金额(单位: 元 保留俩位小数)
# #     )
# #     pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
# #     return jsonify({
# #         'code': 200,
# #         'url': pay_url
# #     })

from tools.comm import get_ali_object
from application.models.users.user import VipRecord
@user_blue.route('/settlement',methods=['POST'])
def settlement():
    # 获取参数
    req = reqparse.RequestParser()
    req.add_argument('userid')
    args = req.parse_args()
    money = 1
    tmoney = money * int(5)
    order_no = str(int(time.time())) + str(args['userid']) + str(random.randint(100, 999))
    # 支付页面 支付
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='购物车订单',  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=tmoney,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code":200,"url":pay_url})

#评论
from application.models.users.user import Comment
from application.models.users.user import db
@user_blue.route("/crecom",methods=['POST'])
def createes():
    data = json.loads(request.data)
    title = data['title']
    userid = data['userid']
    pid = data['pid']
    # userid = int(userid)
    # pid = int(pid)
    print(userid,pid,title)
    if not pid:
        #首个评论
        comm = Comment(title=title,userid=userid,typepid=1,pid=0)
        db.session.add(comm)
        print(">>>>....")
        db.session.commit()
    else:
        com = Comment.query.filter(Comment.id==pid).first()
        print("com",com.id)
        if com:
            coms = Comment(title=title,userid=userid,typepid=2,pid=com.id)
            db.add(coms)
            print(coms,">?")
            coms_info = Comment.query.filter(Comment.pid==pid).first()
            print(coms_info,"///")
            if not coms_info:
                coms.is_last = 1
                print("11")
            else:
                coms.is_last = 0
                print("00")
            db.commit()
        else:
            return jsonify({"code":404,"msg":"评论已删除"})
    return jsonify({"code":200,"msg":"ok"})

#获取评论
def showuser(data):   #封装方法 也可以写进类视图中
    list2=[]
    dict2={}
    for i in data:
        k = i['id']
        dict2[k]=i

    for j in data:
        pid=j['pid']
        if pid == 0:   #如果为空说明是第一级
            list2.append(j)
        else:
            if 'son' not in dict2[pid]:   #判断是否有下级分类
                dict2[pid]['son'] = []
            dict2[pid]['son'].append(j)   #添加进去
    return list2

class Comments(Resource):
    def get(self):
        user_info = Comment.query.all()
        user_data = []
        for i in user_info:
            a = {
                'id':i.id,
                'title': i.title,
                'tcount': i.tcount,
                'tviews': i.tviews,
                'is_last': i.is_last,
                'is_top': i.is_top,
                'userid': i.userid,
                'typepid': i.typepid,
                'pid': i.pid,
            }
            user_data.append(a)
        ss=showuser(user_data)    #调用方法 并传参
        return jsonify({'code':200,'data':ss})
api.add_resource(Comments,"/comment")